<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @author Anh Nguyen <duyanhnguyen@vccorp.vn>
 * @copyright 2012
 * @property Phpmailer $phpmailer PHP Mailer
 */
class Mycommon
{

    private $_CI;

    public function __construct()
    {
        $this->_CI = & get_instance();
    }

    public function loadMail()
    {
        $this->_CI->config->load('email');
        $config = $this->_CI->config->item('mail');
        $this->_CI->load->library('PHPMailer/phpmailer');
        $this->_CI->phpmailer->IsSMTP();
        $this->_CI->phpmailer->SMTPAuth = true;
        $this->_CI->phpmailer->SMTPSecure = $config['SMTPSecure'];
        $this->_CI->phpmailer->Host = $config['host'];
        $this->_CI->phpmailer->Port = $config['port'];
        $this->_CI->phpmailer->Username = $config['username'];
        $this->_CI->phpmailer->Password = $config['password'];
        $this->_CI->phpmailer->SetFrom($config['username'], $config['contentFrom']);
        $this->_CI->phpmailer->CharSet = $config['charset'];
    }

    function isYoutube($url, $type = "videoUrl")
    {
        switch (strtolower($type)) {
            case "videourl" :
                $regex = "https?:\/\/(www.)?youtube.com\/watch\?v=[a-zA-Z0-9\_\-\.]{2,}&?(.*)?";
                break;
            case "channelurl" :
                $regex = "https?:\/\/(www.)?youtube.com\/user\/[a-zA-Z0-9\_\-\.]{2,}\/videos(\?.*)?";
                break;
            case "channeluploads" :
                $regex = "https?:\/\/gdata.youtube.com\/feeds\/(api|base)\/users\/[a-zA-Z0-9\_\-\.]{2,}\/uploads\/?(.*)?";
                break;
            case "playlist" :
                $regex = "https?:\/\/www.youtube.com\/playlist\?list=[a-zA-Z0-9\_\-\.]{18}&?(.*)?";
                break;
            case "playlistrss" :
                $regex = "https?:\/\/gdata.youtube.com\/feeds\/api\/playlists\/[a-zA-Z0-9\_\-\.]{16}\/?";
                break;
        }
        return preg_match("/$regex/i", $url);
    }

    function isUrl($input)
    {
        return preg_match("/^[A-Za-z]+:\/\/[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=#]+$/", $input);
    }

    public function _parseVidYoutube($url)
    {
        $regex = "/https?:\/\/(www.)?youtube.com\/watch\?v=([a-zA-Z0-9\_\-\.]{2,})&?(.*)?/i";
        $matches = array();
        preg_match($regex, $url, $matches);
        return $matches[2];
    }

    public function getThumbVideoYoutube($url)
    {
        if ($this->isYoutube($url)) {
            $vId = $this->_parseVidYoutube($url);
            $numImg = rand(1, 4);
            return "http://img.youtube.com/vi/$vId/$numImg.jpg";
        }
        return false;
    }

    public function getEmbedVideoYoutube($url)
    {
        $tmpSize = unserialize(VIDEO_SIZE);
        $videoSize = $tmpSize['normal'];
        if ($this->isYoutube($url)) {
            $vId = $this->_parseVidYoutube($url);
            return "<object width='{$videoSize['width']}' height='{$videoSize['height']}'>
                        <param name='movie' value='http://www.youtube.com/v/$vId?version=3&amp;hl=en_US'></param>
                        <param name='allowFullScreen' value='true'></param>
                        <param name='allowscriptaccess' value='always'></param>
                        <embed src='http://www.youtube.com/v/$vId?version=3&amp;hl=en_US' type='application/x-shockwave-flash' width='{$videoSize['width']}' height='{$videoSize['height']}' allowscriptaccess='always' allowfullscreen='true'></embed>
                    </object>";
        }
        return false;
    }

    public function authAdmin()
    {
        if (!$this->_CI->session->userdata('u_id') || !$this->_CI->session->userdata('u_acc')) {
            $back = site_url($this->_CI->uri->uri_string());
            $back = str_replace('.html', '', $back);
            $backlink = urlencode($back);
            header('Location: ' . site_url('admin/auth') . '?back_url=' . $backlink);
        }
    }

    function rangeWeek($datestr)
    {
        date_default_timezone_set(date_default_timezone_get());
        $dt = strtotime($datestr);
        $res['start'] = date('N', $dt) == 1 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('last monday', $dt));
        $res['end'] = date('N', $dt) == 7 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('next sunday', $dt));
        return $res;
    }

    public function renderThumbImage($image, $width, $height, $cropFlag = TRUE)
    {
        if (empty($image) || is_null($image)) {
            $image = '';
        }

        if ($image == '') {
            $image = '/images/noImage/no.jpg';
        }

        if ($cropFlag == TRUE) {
            return STATIC_DOMAIN . 'slir/w' . $width . '-h' . $height . '-c' . $width . 'x' . $height . $image;
        } else {
            return STATIC_DOMAIN . 'slir/w' . $width . '-h' . $height . $image;
        }
//        if ($cropFlag == TRUE) {
//            return STATIC_DOMAIN . 'timthumb.php?w=' . $width . '&h=' . $height . '&q=100' . '&src=' . $image;
//        } else {
//            return STATIC_DOMAIN . 'timthumb.php?w=' . $width . '&h=' . $height . '&src=' . $image;
//        }
    }

    public function getLangCode()
    {
        if ($this->_CI->session->userdata('langCode')) {
            $langCode = $this->_CI->session->userdata('langCode');
        } else {
            $langCode = $this->_CI->config->item('language');
            $this->_CI->session->set_userdata('langCode', $langCode);
        }
        return $langCode;
    }

    public function setLangCode($lang)
    {
        $langValid = array(
            'vietnam',
            'english'
        );
        if (!in_array($lang, $langValid)) {
            return false;
        }
        $this->_CI->session->set_userdata('langCode', $lang);
        $this->_CI->load->library('Blockcache');
        $this->_CI->blockcache->save('menubar', '', 0);
        return true;
    }

    public function fetchLangCode($lang)
    {
        $arr = array(
            'vietnam' => 'vn',
            'english' => 'en'
        );
        if (!in_array($lang, array_keys($arr))) {
            return false;
        }
        return $arr[$lang];
    }

    function convertToAlias($title)
    {
        $title = trim($title);
        $strFind = array(
            ': ', ':',
            ' ',
            'đ', 'Đ',
            'á', 'à', 'ạ', 'ả', 'ã', 'Á', 'À', 'Ạ', 'Ả', 'Ã', 'ă', 'ắ', 'ằ', 'ặ', 'ẳ', 'ẵ', 'Ă', 'Ắ', 'Ằ', 'Ặ', 'Ẳ', 'Ẵ', 'â', 'ấ', 'ầ', 'ậ', 'ẩ', 'ẫ', 'Â', 'Ấ', 'Ầ', 'Ậ', 'Ẩ', 'Ẫ',
            'ó', 'ò', 'ọ', 'ỏ', 'õ', 'Ó', 'Ò', 'Ọ', 'Ỏ', 'Õ', 'ô', 'ố', 'ồ', 'ộ', 'ổ', 'ỗ', 'Ô', 'Ố', 'Ồ', 'Ộ', 'Ổ', 'Ỗ', 'ơ', 'ớ', 'ờ', 'ợ', 'ở', 'ỡ', 'Ơ', 'Ớ', 'Ờ', 'Ợ', 'Ở', 'Ỡ',
            'é', 'è', 'ẹ', 'ẻ', 'ẽ', 'É', 'È', 'Ẹ', 'Ẻ', 'Ẽ', 'ê', 'ế', 'ề', 'ệ', 'ể', 'ễ', 'Ê', 'Ế', 'Ề', 'Ệ', 'Ể', 'Ễ',
            'ú', 'ù', 'ụ', 'ủ', 'ũ', 'Ú', 'Ù', 'Ụ', 'Ủ', 'Ũ', 'ư', 'ứ', 'ừ', 'ự', 'ử', 'ữ', 'Ư', 'Ứ', 'Ừ', 'Ự', 'Ử', 'Ữ',
            'í', 'ì', 'ị', 'ỉ', 'ĩ', 'Í', 'Ì', 'Ị', 'Ỉ', 'Ĩ',
            'ý', 'ỳ', 'ỵ', 'ỷ', 'ỹ', 'Ý', 'Ỳ', 'Ỵ', 'Ỷ', 'Ỹ'
        );
        $strReplace = array(
            '-', '-',
            '-',
            'd', 'd',
            'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
            'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o',
            'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e',
            'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u',
            'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i',
            'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y'
        );

        return strtolower(preg_replace('/[^a-z0-9\-]+/i', '', str_replace($strFind, $strReplace, $title)));
    }

    function objectsIntoArray($arrObjData, $arrSkipIndices = array())
    {
        $arrData = array();

        // if input is object, convert into array
        if (is_object($arrObjData)) {
            $arrObjData = get_object_vars($arrObjData);
        }

        if (is_array($arrObjData)) {
            foreach ($arrObjData as $index => $value) {
                if (is_object($value) || is_array($value)) {
                    $value = $this->objectsIntoArray($value, $arrSkipIndices); // recursive call
                }
                if (in_array($index, $arrSkipIndices)) {
                    continue;
                }
                $arrData[$index] = $value;
            }
        }
        return $arrData;
    }

    public function initMailer()
    {
        $this->_CI->load->library('PHPMailer/phpmailer');
        $this->_CI->load->config('email');
        $config = $this->_CI->config->item('mail');
        $this->_CI->phpmailer->IsSMTP();
        $this->_CI->phpmailer->SMTPDebug = 0;
        $this->_CI->phpmailer->SMTPAuth = true;
        $this->_CI->phpmailer->SMTPSecure = 'ssl';
        $this->_CI->phpmailer->Host = $config['host'];
        $this->_CI->phpmailer->Port = $config['port'];
        $this->_CI->phpmailer->Username = $config['username'];
        $this->_CI->phpmailer->Password = $config['password'];
        $this->_CI->phpmailer->CharSet = 'utf-8';
        $this->_CI->phpmailer->SetFrom($config['username'], $config['contentFrom']);
        $this->_CI->phpmailer->AddAddress($config['adminEmail']);
    }

    public function resetCache($dir)
    {
        $documentRoot = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR;
        $files = scandir($documentRoot . $dir);
        $notDelete = array('.', '..', '.htaccess', 'index.html');
        foreach ($files as $file) {
            if(!in_array($file, $notDelete))
                @unlink($documentRoot . $dir . DIRECTORY_SEPARATOR . $file);
        }
    }

}

?>
